package com.zhouxiaoge.logs.config.logs;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

@Slf4j
public class MyLogInterceptor extends HandlerInterceptorAdapter {
    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            MyLog myLog = method.getAnnotation(MyLog.class);
            if (null != myLog) {
                long startTime = System.currentTimeMillis();
                startTimeThreadLocal.set(startTime);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        String requestURI = request.getRequestURI();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String parameters = null;
        if (!parameterMap.isEmpty()) {
            System.out.println(request.getParameterMap());
            parameters = JSON.toJSONString(request.getParameterMap());
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            MyLog myLog = method.getAnnotation(MyLog.class);
            if (null != myLog) {
                Long startTime = startTimeThreadLocal.get();
                long endTime = System.currentTimeMillis();
                long expendTime = endTime - startTime;
                String methodName = method.getDeclaringClass().getName() + "#" + method.getName();
                String methodDesc = myLog.desc();

                log.info("\n描述：{}\n路径: {}\n方法: {}\n参数：{}\n耗时：{}", methodDesc, requestURI, methodName, parameters, expendTime);
            }
        } else {
            log.info("\n描述：{}\n路径: {}\n参数：{}", "错误的访问", requestURI, parameters);
        }
        super.postHandle(request, response, handler, modelAndView);
    }
}
